const App = getApp()
const util = require('../../../utils/util.js')
Page({
  data: {
    billType: 0,
    orderType: '',
    desc: '',
    date: '',
    time: '',
    lock: true,
    checked: false,
    totalAmount: '', // 实际支付
    total: '', // 合计
    intMoney: 0,
    intVal: '',
    userInfo: {
      discount: 0, // 用户优惠金额 
      heavydiscount: '', //大客户优惠金额
      heavydiscountType: '', //大客户折扣类型
      linkman: '', // 联系人 
      phone: '', // 联系电话 
      appointmentTime: '', // 预约时间
      fullCuts: [], //满减活动
    },
    //满减活动
    fullcut: {
      cash: 0, //优惠金额
      fullCutInfo: '', //优惠信息：比如：满5.00块减1.00元
      fullCutTime: '', //活动剩余天数：比如：剩余14天结束
      meet: 0, //花费金额：比如：5.00元
      postage: 0, //邮费
    },
    status: 0,
    status2: 0,
    png: false,
    showInvoice: false,
    showIntegral: false,
    couponsList: [],
    coupons: '',
    couponsFee: 0,
    couponsId: 0,
    billId: 0,
    discounts: 0
  },
  onLoad(option) {

    console.log(666, option)
    // debugger


    let defaultCar = wx.getStorageSync('defaultCar');
    let products = wx.getStorageSync('products');
    let userId = wx.getStorageSync('userId');
    let agent = wx.getStorageSync('agent');
    let goodsInfo = [];
    let intMoney = 0;
    let nowDate = new Date().getTime();

    products.forEach(item => {
      item.pricetotal = (Number(item.price) * item.num).toFixed(2)
      goodsInfo.push({
        goodsId: item.id,
        num: item.num
      })
    })
    this.setData({

      merchant: option,
      defaultCar,
      products,
      goodsInfo,
      userId,
      agent,
      'userInfo.carCode': defaultCar.carCode,
      'userInfo.linkman': defaultCar.linkman,
      'userInfo.phone': defaultCar.phone,
      'userInfo.appointmentTime': option.date + ' ' + option.time,
      intMoney: intMoney.toFixed(2)
    })
    this.discount()
    this.userInfo()

    var canshu = JSON.parse(this.data.merchant.canshu)
    // debugger
    var ddaq = canshu.qian * canshu.zhekou * 0.01
// debugger
    this.setData({
      qqqqq:ddaq
    })
  },
  onShow() {
    // this.discount()
    let billType = parseInt(wx.getStorageSync('billTypeId'));
    if (!billType) {
      billType = 0;
    }
    this.setData({
      billType,
      billId: billType
    });

  },
  discount() { // 优惠活动
    let {
      userId,
      agent
    } = this.data
    let params = {
      buyerId: userId,
      sellerId: agent.id,
      type: 0
    }
    App.HttpService.discount(params).then(res => {
      let data = res.data.data
      if (res.data.code == 200) {

        //判断是否满足大客户折扣
        if (data.isdiscount == 1) {
          this.setData({
            'userInfo.heavydiscount': data.discountValue,
            'userInfo.heavydiscountType': data.discountType,
          })
        }

        //判断用户状态，与代理商状态,是否满足首单立减
        if (data.buyerStatus == 1 && data.sellerStatus == 1) {
          this.setData({
            'userInfo.discount': data.sellerValue
          })
        }
        //查询是否存在满减活动
        if (data.fullCut.length > 0) {
          let fullCuts = [];
          data.fullCut.forEach(item => {
            //判断符合当前订单金额的满减活动
            fullCuts.push(item);
            // this.setData({
            //   'fullCut.cash' :item.cash,
            //   'fullcut.fullCutInfo' :item.fullCutInfo,
            //   'fullcut.fullCutTime' :item.fullCutTime,
            //   'fullcut.meet' : item.meet,
            //   'fullcut.postage' :item.postage,
            // })
            // fullCuts.push(this.data.fullCut)
          });
          this.setData({
            'userInfo.fullCuts': fullCuts
          })
          console.log(this.data.userInfo.fullCuts);
        }
        this.calAmount()


      }
    })
  },
  userInfo() { // 获取积分
    let {
      userId
    } = this.data
    App.HttpService.userInfo({
      userId: userId
    }).then(res => {
      let data = res.data
      if (data.code == 200) {
        let integral = data.data.consumeInfo
        integral.score = data.data.userInfo.score
        this.setData({
          integral: integral
        })
      }
    })
  },
  calAmount() { //计算总价格
    let {
      userInfo,
      products
    } = this.data
    let total = 0

    products.forEach(item => {
      total += item.price
    })
    //判断大客户优惠
    let temp_heavydiscount = 0;
    if (userInfo.heavydiscountType == 0) {
      temp_heavydiscount = total * userInfo.heavydiscount / 100;
    } else {
      temp_heavydiscount = userInfo.heavydiscount;
    }
    total = total - temp_heavydiscount;
    //定义满减金额值是否有满足
    let fullcuts = [] = this.data.userInfo.fullCuts
    let cash = 0;
    let temp = 0;
    fullcuts.forEach(item => {
      if (item.meet <= total) {
        if (item.meet >= temp) {
          temp = item.meet;
          cash = item.cash;
          this.setData({
            'fullcut.fullCutInfo': item.fullCutInfo,
            'fullcut.fullCutTime': item.fullCutTime
          })
        }
      }
    });
    total = total - cash;
    this.setData({
      discounts: userInfo.discount + temp_heavydiscount + cash
    })
    //总金额减去首单立减
    total = total - userInfo.discount;
    total = total.toFixed(2);
    //如果优惠活动大于支付金额则支付0.01
    if (total < 0) {
      total = 0.01
    }
    this.setData({
      total,
      totalAmount: total
    })
    // 查询优惠券个数
    this.chaxunyouhuiquan();
  },
  // 计算出最后支付的价格
  calTotalAmount() {
    let {
      totalAmount,
      total,
      couponsFee,
      intMoney
    } = this.data;
    totalAmount = total - couponsFee - intMoney;
    this.setData({
      totalAmount
    });
  },
  inputBlur(e) { // 失去焦点时间
    let {
      key
    } = e.currentTarget.dataset
    let {
      value
    } = e.detail
    this.setData({
      [key]: value
    })
  },
  bindTextAreaBlur(e) { // 监听到新输入的值
    this.setData({
      desc: e.detail.value
    })
  },
  integralBlur(e) {
    let {
      value
    } = e.detail
    let {
      integral,
      totalAmount,
      couponsFee
    } = this.data // total 订单金额
    let scoreVal = (integral.score * integral.coinValue / integral.countsValue).toFixed(2)
    // 所有积分兑换金额
    let integralVal = (Number(value) * integral.coinValue / integral.countsValue).toFixed(2)
    // 输入积分兑换金额
    let amount = totalAmount - couponsFee
    if (scoreVal - integralVal > 0) { // 输入积分小于所有积分  输入合法
      if (amount - integralVal > 0) { // 输入积分小于订单金额
        this.setData({
          intMoney: integralVal,
          intVal: value
        })
      } else { // 输入积分大于订单金额 输入积分==订单金额
        let score = Math.ceil(amount * integral.countsValue / integral.coinValue)
        this.setData({
          intMoney: amount,
          intVal: score
        })
      }
    } else { // 输入积分大于所有积分 输入不合法 取所有积分
      if (amount - scoreVal > 0) { // 所有积分小于订单金额
        this.setData({
          intMoney: scoreVal,
          intVal: integral.score
        })
      } else { // 所有积分大于订单金额 所有积分==订单金额
        let score = Math.ceil(amount * integral.countsValue / integral.coinValue)
        this.setData({
          intMoney: amount,
          intVal: score
        })
      }
    }
    this.calTotalAmount();
  },
  // redirectTo(e) {
  //   App.WxService.redirectTo('/pages/address/confirm/index', {
  //     ret: this.data.address_id
  //   })
  // },
  addOrder(e) {
    console.log(e)
    var canshu = JSON.parse(this.data.merchant.canshu)

    //  当前ID
    let buyerId = wx.getStorageSync('userId');
    let sellerId = wx.getStorageSync('agent').id

    // 电子券id
    let electronicId = this.data.merchant.s_id
    // carid 当前车辆id
    let buyerCarId = this.data.defaultCar.carModelId
    // 当前车辆公里数
    let miles = this.data.defaultCar.miles
    // shopId 店铺id
    let shopId = this.data.merchant.merchantId
    // 订单的时间
    let appointmentTime = this.data.userInfo.appointmentTime + ':00'

    // 三个订单信息
    let consignee = this.data.userInfo.linkman
    let orderPhone = this.data.userInfo.phone
    // 当前车辆车牌号
    var carCode = this.data.defaultCar.carCode
    var originalPrice = canshu.qian
    // 原价
    var discount = canshu.zhekou
    //  折扣
    var pay = canshu.qian * canshu.zhekou * 0.01
    //  现价

    let memo = this.data.beizhu
    let fromId = e.detail.formId

    if (!(/^1[3456789]\d{9}$/.test(orderPhone))) {
      this.alert("手机号码有误，请重填");
    }

    App.HttpService.dianziquanshiy({
      buyerId,
      electronicId,
      shopId,
      orderPhone,
      consignee,
      appointmentTime,
      memo,
      fromId,
      miles,
      buyerCarId,
      sellerId,
      carCode,
      originalPrice,
      discount,
      pay
    }).then(res => {
      console.log(res)

      var ddd = res.data.code
      if (ddd == 200) {

        var config = res.data.data
        let payconfig = {
          timeStamp: config.timeStamp,
          nonceStr: config.nonceStr,
          package: config.package,
          signType: config.signType,
          paySign: config.paySign,
        }
        wx.requestPayment({
          timeStamp: config.timeStamp,
          nonceStr: config.nonceStr,
          package: config.package,
          signType: config.signType,
          paySign: config.paySign,
          success(res) {
            wx.showToast({
              title: '支付成功',
              duration: 1000,
            })
            wx.showModal({
              title: '温馨提示',
              content: '服务预约成功',
              success(ss) {
                if (ss.confirm) {
                  console.log('用户点击确定')
                  wx.navigateBack({
                    delta: 3
                  })
                } else if (ss.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
            console.log(res, "成功")
          },
          fail(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'loading',
              duration: 1000,
            })
            console.log(res, "支付失败")
          }
        })
      } else {

        wx.showModal({
          title: '温馨提示',
          content: '服务预约失败',
          success(ss) {
            if (ss.confirm) {
              console.log('用户点击确定')
              wx.navigateBack({
                delta: 3
              })
            } else if (ss.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    });
  },
  alert(msg) {
    wx.showToast({
      title: msg,
      image: '../../../assets/images/warning.png',
      duration: 1500
    })
  },
  clear() {
    App.HttpService.clearCartByUser().then(res => {
      const data = res.data
    })
  },
  // 跳转到商家
  toMerchant(e) {
    let shopId = e.currentTarget.dataset.id;
    let distance = e.currentTarget.dataset.distance;
    wx.navigateTo({
      url: `/pages/merchantsList/detail/detail?shopId=${shopId}&distance=${distance}`,
    })
  },
  // 购物车详情弹窗
  setModalStatus2(e) {
    // let { status, index } = e.currentTarget.dataset
    let status = !this.data.status;
    this.setData({
      png: !this.data.png
    });
    this.setData({
      status
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData2: animation.export()
    })
    if (status == 1) {
      this.setData({
        showModalStatus2: true
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status == 0) {
        this.setData({
          showModalStatus2: false
        })
      }
    }.bind(this), 100)
  },
  // 隐藏购物车弹窗
  setModalStatus3(e) {
    // let { status, index } = e.currentTarget.dataset
    let status = 0;
    this.setData({
      png: !this.data.png
    });
    this.setData({
      status
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData2: animation.export()
    })
    if (status == 0) {
      this.setData({
        showModalStatus2: false
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status == 0) {
        this.setData({
          showModalStatus2: false
        })
      }
    }.bind(this), 100)
  },

  // 查询优惠券
  chaxunyouhuiquan: function() {
    let userId = this.data.userId;
    let amount = this.data.totalAmount;
    let sellerId = this.data.agent.id;
    App.HttpService.getCoupons({
      userId,
      amount: amount,
      sellerId,
      couponsType: 1
    }).then(res => {
      if (res.data.code == 200) {
        let data = res.data.data;
        // for (let i = 0; i < data.length; i++) {
        //   if (data[i].id == this.data.coupons) {
        //     data[i].checked = true;
        //   } else {
        //     data[i].checked = false;
        //   }
        // }
        this.setData({

          tiaoshu: data.length
        });
      }
    });

  },

  // 优惠券弹窗
  setModalStatus4(e) {
    console.log(e)
    let userId = this.data.userId;
    let amount = this.data.totalAmount;
    let sellerId = this.data.agent.id;

    App.HttpService.getCoupons({
      userId,
      amount: amount,
      sellerId,
      couponsType: 1
    }).then(res => {
      if (res.data.code == 200) {
        let data = res.data.data;
        for (let i = 0; i < data.length; i++) {
          if (data[i].id == this.data.coupons) {
            data[i].checked = true;
          } else {
            data[i].checked = false;
          }
        }
        this.setData({
          couponsList: data,
          tiaoshu: data.length
        });

      }
    });
    let status2 = 1;
    this.setData({
      status2
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export()
    })
    if (status2 == 1) {
      this.setData({
        showModalStatus: true
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status2 == 0) {
        this.setData({
          showModalStatus: false
        })
      }
    }.bind(this), 100)
  },
  // 隐藏优惠券弹窗
  setModalStatus5(e) {
    // let { status, index } = e.currentTarget.dataset
    let status2 = 0;
    this.setData({
      status2
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export()
    })
    if (status2 == 0) {
      this.setData({
        showModalStatus: false
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (status2 == 0) {
        this.setData({
          showModalStatus: false
        })
      }
    }.bind(this), 100)
  },
  // 选择优惠券
  chooseCoupons(e) {
    let coupons = e.currentTarget.dataset.id;
    let couponsFee = e.currentTarget.dataset.discountsfee;
    let checkedStatus = e.currentTarget.dataset.checked;
    if (checkedStatus) {
      this.setData({
        coupons: '',
        couponsFee: 0,
        couponsId: 0
      });
    } else {
      this.setData({
        coupons,
        couponsFee,
        couponsId: coupons
      });
    }
    this.setModalStatus5();
    this.calTotalAmount();
  },
  // 是否需要发票
  chooseInvoice(e) {
    this.setData({
      showInvoice: e.detail.value
    });
  },
  // 是否使用积分
  chooseIntegral(e) {
    this.setData({
      showIntegral: e.detail.value
    });
    if (!e.detail.value) {
      this.setData({
        intMoney: 0.00,
        totalAmount: this.data.total - this.data.couponsFee
      });
    }
  },
  // 跳转到发票管理
  toInvoice() {
    wx.navigateTo({
      url: '/pages/invoice/invoice',
    })
  },
  // 监听输入联系人
  linkmanInput(e) {
    this.setData({
      'userInfo.linkman': e.detail.value
    });
  },
  // 监听输入联系电话
  phoneInput(e) {
    this.setData({
      "userInfo.phone": e.detail.value
    });
  },
  //备注
  beizhu: function(e) {
    console.log(e)
    this.setData({
      beizhu: e.detail.value
    })
  },
})